/**
 * Created by eaTong on 2018/4/24 .
 * Description:
 */
import {Platform} from 'react-native';
import {Toast} from 'native-base';
import qs from 'qs';
import appConfig from './config';


export default function ajax(config) {
  const {url, data, headers} = config;
  const method = (config.method || 'post').toUpperCase();

  return new Promise(((resolve, reject) => {
    let finalUrl = appConfig.host + url;
    let body;
    if (method === 'GET') {
      finalUrl += `?${qs.stringify(data)}`
    } else {
      body = JSON.stringify(data);
    }
    const option = {
      method,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      credentials: 'include',
      body
    };
    fetch(finalUrl, option)
      .then(response => {
        const status = ~~response.status;
        console.log(finalUrl , response)
        if(status === 200){
          return response.json();
        }else{
          switch (status) {
            case 401:
              Toast.show({
                text: "登录过期!",
                duration: 3000,
                position: "top"
              });
              break;
            case 404:
              Toast.show({
                text: "接口不存在!",
                duration: 3000,
                position: "top"
              });
              break;
            case 500:
              Toast.show({
                text: '500：内部服务器错误',
                duration: 3000,
                position: "top"
              });
              break;
            default:
              Toast.show({
                text: '服务器错误',
                duration: 3000,
                position: "top"
              });
          }
          reject(response.data);
        }
      })
      .then((resultData) => {
        if (resultData.status === 1) {
          resolve(resultData.data)
        } else {
          Toast.show({
            text: resultData.msg,
            duration: 3000,
            position: "top"
          });
          reject();
        }

      })
  }));
};
